// SQLite 数据库-示例
package main

import (
	"database/sql"
	"fmt"
	"time"

	_ "github.com/mattn/go-sqlite3"
)

func main() {
	db, err := sql.Open("sqlite3", "./foo.db")
	checkErr(err)

	// insert
	stmt, err := db.Prepare("INSERT INTO user_info(username, departname, created) values(?, ?, ?)")
	checkErr(err)

	res, err := stmt.Exec("astaxie", "研发部门", "2020-10-10")
	checkErr(err)

	id, err := res.LastInsertId()
	checkErr(err)

	fmt.Println("insert:", id)

	// update
	stmt, err = db.Prepare("UPDATE user_info SET username=? WHERE uid=?")
	checkErr(err)

	res, err = stmt.Exec("astaxie update", id)
	checkErr(err)

	affect, err := res.RowsAffected()
	checkErr(err)

	fmt.Println("update:", affect)

	// select
	rows, err := db.Query("SELECT * FROM  user_info")
	checkErr(err)

	for rows.Next() {
		var uid int
		var username string
		var department string
		var created time.Time

		err = rows.Scan(&uid, &username, &department, &created)
		checkErr(err)

		fmt.Println("uid:", uid)
		fmt.Println("username:", username)
		fmt.Println("department:", department)
		fmt.Println("created:", created)
	}

	// delete
	stmt, err := db.Prepare("DELETE FROM  user_info WHERE uid=?")
	checkErr(err)

	res, err := stmt.Exec(id)
	checkErr(err)

	affect, err = res.RowsAffected()
	checkErr(err)

	fmt.Println("delete:", affect)

	db.Close()
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}